package logic

import (
	"context"
	"fmt"
	"pinduoduo/models"

	"pinduoduo/userrpc/internal/svc"
	"pinduoduo/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserLoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
	return &UserLoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserLoginLogic) UserLogin(in *userrpc.UserLoginRequest) (*userrpc.UserLoginResponse, error) {
	// todo: add your logic here and delete this line

	captcha := in.Captcha
	get := models.Rdb.Get("captchalogin" + in.Mobile)
	if get.Val() != captcha {
		return nil, fmt.Errorf("验证码有误请重新填写")
	}

	fmt.Println(get)
	code := in.SmsCode
	cmd := models.Rdb.Get("sendSmslogin" + in.Mobile)
	if cmd.Val() != code {
		return nil, fmt.Errorf("短信验证码有误请重新填写")
	}

	fmt.Println(cmd)
	var user models.User
	err := models.Db.Debug().Where("mobile = ?", in.Mobile).Find(&user).Error
	if err != nil {
		return nil, err
	}
	if user.ID == 0 {
		return nil, fmt.Errorf("用户不存在")
	}
	if user.Password != in.Password {
		return nil, fmt.Errorf("密码填写错误请重新输入")
	}
	return &userrpc.UserLoginResponse{Id: int64(user.ID), Mobile: user.Mobile}, nil
}
